package cn.s1995.sloth.bizs.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@Component
public class ExchangeRateUtil {

	private final String USD_TO_CNY_KEY = "rate:usd:cny";
	private final String API_KEY = "1feaa5e2be110bc2b07b21dc";
	private final String API_URL = "https://v6.exchangerate-api.com/v6/" + API_KEY + "/latest/USD";

	@Resource
	private RedisUtil redisUtil;

	public BigDecimal getUsdtoCnyRate() {
		BigDecimal rate = redisUtil.getBigDecimal(USD_TO_CNY_KEY);
		if(ObjectUtil.isNotNull(rate) && !(rate.compareTo(BigDecimal.ZERO) == 0)) {
			return rate;
		}
		try {
			double fetchUsdToCnyRate = fetchUsdToCnyRate();
			redisUtil.set(USD_TO_CNY_KEY, fetchUsdToCnyRate, 86400);
			return new BigDecimal(fetchUsdToCnyRate);
		} catch (Exception e) {
			log.error("获取汇率失败，默认汇率", e);
			return new BigDecimal(7);
		}
	}


    private double fetchUsdToCnyRate() throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String responseJson = "";
        String line;
        while ((line = br.readLine()) != null) {
            responseJson += line;
        }

        conn.disconnect();

        // 使用Fastjson解析JSON响应
        JSONObject responseObj = JSONUtil.parseObj(responseJson);
        JSONObject rates = responseObj.getJSONObject("conversion_rates");
        double cnyRate = rates.getDouble("CNY"); // 假设API返回的JSON结构包含rates.CNY作为人民币汇率
        return cnyRate;
    }

    /**
     * 汇率换算
     * @param amount
     * @param rate
     * @return
     */
    public BigDecimal convertRate(BigDecimal amount, BigDecimal rate) {
        if (amount == null) {
            return null;
        }
        return amount.divide(rate, 2, RoundingMode.HALF_UP);
    }
}
